package runnable;

import java.io.File;

import javax.swing.SwingUtilities;

import utils.SSHUtils;
import utils.Utils;
import jsonobj.JobInfo;
import data.JobData;
import gui.MainPanel;
import gui.toolpanels.CNode;
import guiobj.JobPanelController;
import guiobj.SubmitPanelInfo;

public class SubmitJobThread implements Runnable{
	MainPanel mp;
	SubmitPanelInfo s;
	public SubmitJobThread(MainPanel m)
	{
		this.mp = m;
		s = new SubmitPanelInfo();
    	s.getInfo(m);
    	
	}
	@Override
	public void run() {
		String filename;
		if(new File(s.filedir).isDirectory())
			filename = Utils.zip(s.filedir);
		else
			filename  = new File(s.filedir).getName();
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				mp.jProgressBar1.setValue(10);
				mp.infoLab.setText("Creating job directory");
			}
		});
		Utils.out("Uploading file to SSH server");
		if (SSHUtils.CmdTo("mkdir ~/" + s.jname) == null) {
			Utils.out("Error creating dir on SSH server");
			return;
		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				mp.jProgressBar1.setValue(40);
				mp.infoLab.setText("Uploading file to server");
			}
		});
		if (!SSHUtils.ScpTo(s.filedir, "~/" + s.jname + "/"
				+ filename )) {
			
			Utils.out("Error uploading file to SSH server");
			return;
		}
		s.filedir = new File(s.filedir).getName();
		final String fname = filename;
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				CNode n = new CNode(s.jname);
				n.add(new CNode(fname));
				Utils.root.add(n);
				mp.ftp.insert(n);
				mp.jProgressBar1.setValue(80);
				mp.infoLab.setText("Sending job submission request");
			}
		});
		try {
			Utils.ws.send(s);
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {

					mp.jProgressBar1.setValue(100);
					mp.infoLab.setText("Job submitted!");
					JobPanelController.addJobInfo(mp, s);
					Utils.jobs.put(s.jname, s);
				}
			});
			Thread.sleep(1000);
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					mp.jProgressBar1.setValue(0);
					mp.subB.setEnabled(true);
					mp.infoLab.setText("Click Submit to submit a job");
				}
			});
		} catch (Exception e) {
			mp.subB.setEnabled(true);
			e.printStackTrace();
		}
		Utils.out("Done");
		
		
	}

}
